//
//  BRScanResultViewController.m
//  BrezzeSaaS
//
//  Created by IOS on 2025/01/27.
//  Copyright © 2025 Brezze GWG. All rights reserved.
//

#import "BRScanResultViewController.h"
#import "BRScanResultModel.h"
#import "BRAPI.h"
#import "BRRequestManager.h"
#import "BRHud.h"
#import "BRRentOrderViewController.h"
#import "BRTools.h"
#import <SDWebImage/SDWebImage.h>

@interface BRScanResultViewController ()

@property (nonatomic,strong) UIScrollView *scrollView;
@property (nonatomic,strong) UIView *contentView;
@property (nonatomic,strong) UIImageView *topImageView;
@property (nonatomic,strong) UIView *cardView;
@property (nonatomic,strong) QMUILabel *billingRulesLabel;
@property (nonatomic,strong) QMUIButton *confirmBtn;
@property (nonatomic,strong) QMUIButton *scanAgainBtn; // 再次扫码按钮
@property (nonatomic,strong) BRScanResultModel *resultModel;
@property (nonatomic,strong) QMUILabel *errorLabel; // 错误提示标签
@property (nonatomic,strong) UIView *adapterContainer; // 适配接口容器（用于隐藏/显示）
@property (nonatomic,strong) QMUILabel *adapterTitleLabel; // 适配接口标题（用于隐藏/显示）
@property (nonatomic,strong) QMUILabel *billingTitleLabel; // 计费规则标题（用于隐藏/显示）
@property (nonatomic,assign) NSInteger errorCode; // 记录错误码

@end

@implementation BRScanResultViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = Localized(@"scan_result_title");
    // 设置页面背景色为 #f3f4f5
    self.view.backgroundColor = UIColorMakeWithRGBA(243, 244, 245, 1);
    // 初始化错误码
    self.errorCode = 0;
    [self setUI];
    [self requestData];
}

#pragma mark - UI Setup
- (void)setUI {
    // 页面背景色已在viewDidLoad中设置
    self.view.backgroundColor = UIColorMakeWithRGBA(243, 244, 245, 1);
    
    // 滚动视图
    self.scrollView = [[UIScrollView alloc] init];
    self.scrollView.backgroundColor = UIColorClear;
    self.scrollView.showsVerticalScrollIndicator = NO;
    [self.view addSubview:self.scrollView];
    [self.scrollView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.offset(0);
        make.bottom.equalTo(self.view).offset(-(kSafeAreaBottomHeight + 60));
    }];
    
    // 内容视图
    self.contentView = [[UIView alloc] init];
    self.contentView.backgroundColor = UIColorClear;
    [self.scrollView addSubview:self.contentView];
    [self.contentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.scrollView);
        make.width.equalTo(self.scrollView);
    }];
    
    // 顶部图片
    self.topImageView = [[UIImageView alloc] init];
    self.topImageView.contentMode = UIViewContentModeScaleAspectFill;
    self.topImageView.clipsToBounds = YES;
    self.topImageView.backgroundColor = UIColorMakeWithRGBA(255, 165, 0, 0.3); // 橙色占位背景
    // 设置本地图片（尝试多种方式加载）
    UIImage *localImage = nil;
    // 方式1: 尝试直接使用图片名（如果图片在bundle中）
    localImage = [UIImage imageNamed:@"64217baca49f7eb9b7e7abc1f8c1dae6"];
    // 方式2: 如果方式1失败，尝试从文件系统加载
    if (!localImage) {
        NSString *imagePath = [[NSBundle mainBundle] pathForResource:@"64217baca49f7eb9b7e7abc1f8c1dae6" ofType:@"jpg"];
        if (imagePath) {
            localImage = [UIImage imageWithContentsOfFile:imagePath];
        }
    }
    // 方式3: 如果还是找不到，尝试从指定目录加载
    if (!localImage) {
        NSString *imagePath = [[NSBundle mainBundle] pathForResource:@"64217baca49f7eb9b7e7abc1f8c1dae6" ofType:@"jpg" inDirectory:@"Class/Scan/Controller"];
        if (imagePath) {
            localImage = [UIImage imageWithContentsOfFile:imagePath];
        }
    }
    // 如果都找不到，使用占位图
    if (localImage) {
        self.topImageView.image = localImage;
    } else {
        self.topImageView.image = [UIImage imageNamed:@"home_help"]; // 使用占位图
    }
    [self.contentView addSubview:self.topImageView];
    [self.topImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.offset(0);
        make.height.mas_equalTo(248); // 200 + 48 = 248
        make.width.mas_equalTo(kScreenWidth);
    }];
    
    // 机柜SN标签（显示在图片右上角）
    QMUILabel *snLabel = [[QMUILabel alloc] init];
    snLabel.backgroundColor = UIColorMakeWithRGBA(0, 0, 0, 0.6);
    snLabel.textColor = UIColorWhite;
    snLabel.font = [UIFont fontM:14];
    snLabel.text = [NSString stringWithFormat:@"%@%@", Localized(@"scan_result_stationSN"), self.deviceId ?: @"--"];
    snLabel.textAlignment = NSTextAlignmentCenter;
    snLabel.layer.cornerRadius = 4;
    snLabel.layer.masksToBounds = YES;
    [self.topImageView addSubview:snLabel];
    [snLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.offset(16);
        make.right.offset(-16);
        make.height.mas_equalTo(28);
        make.width.mas_equalTo(120);
    }];
    
    // 卡片视图
    self.cardView = [[UIView alloc] init];
    self.cardView.backgroundColor = UIColorWhite;
    self.cardView.layer.cornerRadius = 16;
    self.cardView.layer.masksToBounds = YES;
    [self.contentView addSubview:self.cardView];
    [self.cardView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.topImageView.mas_bottom).offset(28); // -20 + 48 = 28
        make.left.offset(14);
        make.right.offset(-14);
        make.bottom.equalTo(self.contentView).offset(-20);
    }];
    
    // 适配接口标题
    self.adapterTitleLabel = [[QMUILabel alloc] init];
    self.adapterTitleLabel.text = Localized(@"scan_result_adapterTitle");
    self.adapterTitleLabel.font = [UIFont fontB:16];
    self.adapterTitleLabel.textColor = UIColor.qd_titleTextColor;
    [self.cardView addSubview:self.adapterTitleLabel];
    [self.adapterTitleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.offset(24);
        make.left.offset(20);
        make.right.offset(-20);
    }];
    
    // 适配接口选项（写死，都是开启状态）
    NSArray *adapterTypes = @[@"iOS", @"Type C", @"Android"];
    NSArray *adapterIcons = @[@"ios_icon", @"typec_icon", @"android_icon"]; // 使用本地图片文件
    
    self.adapterContainer = [[UIView alloc] init];
    [self.cardView addSubview:self.adapterContainer];
    [self.adapterContainer mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.adapterTitleLabel.mas_bottom).offset(16);
        make.left.offset(20);
        make.right.offset(-20);
        make.height.mas_equalTo(80); // 增加高度以适应开关
    }];
    
    CGFloat adapterItemWidth = (kScreenWidth - 28 - 40) / 3.0;
    for (NSInteger i = 0; i < adapterTypes.count; i++) {
        UIView *adapterItem = [self createAdapterItem:adapterTypes[i] icon:adapterIcons[i]];
        [self.adapterContainer addSubview:adapterItem];
        [adapterItem mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.offset(i * adapterItemWidth);
            make.top.bottom.offset(0);
            make.width.mas_equalTo(adapterItemWidth);
        }];
    }
    
    // 计费规则标题（增加间距，避免重叠）
    self.billingTitleLabel = [[QMUILabel alloc] init];
    self.billingTitleLabel.text = Localized(@"scan_result_billingRules");
    self.billingTitleLabel.font = [UIFont fontB:14]; // 14px，加粗
    self.billingTitleLabel.textColor = UIColorMakeWithRGBA(51, 51, 51, 1); // #333
    [self.cardView addSubview:self.billingTitleLabel];
    [self.billingTitleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.adapterContainer.mas_bottom).offset(32); // 增加间距到32，避免重叠
        make.left.offset(20);
        make.right.offset(-20);
    }];
    
    // 计费规则内容
    self.billingRulesLabel = [[QMUILabel alloc] init];
    self.billingRulesLabel.font = [UIFont fontM:12]; // 12px
    self.billingRulesLabel.textColor = UIColorMakeWithRGBA(102, 102, 102, 1); // #666
    self.billingRulesLabel.numberOfLines = 0;
    self.billingRulesLabel.text = @"--";
    // 设置行高为1.6
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    paragraphStyle.lineHeightMultiple = 1.6;
    NSMutableAttributedString *attributedText = [[NSMutableAttributedString alloc] initWithString:self.billingRulesLabel.text];
    [attributedText addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, attributedText.length)];
    self.billingRulesLabel.attributedText = attributedText;
    [self.cardView addSubview:self.billingRulesLabel];
    [self.billingRulesLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.billingTitleLabel.mas_bottom).offset(12); // marginBottom 12px
        make.left.offset(20);
        make.right.offset(-20);
        make.bottom.offset(-24);
    }];
    
    // 错误提示标签（默认隐藏）
    self.errorLabel = [[QMUILabel alloc] init];
    self.errorLabel.font = [UIFont fontM:16];
    self.errorLabel.textColor = UIColorMakeWithRGBA(51, 51, 51, 1); // #333
    self.errorLabel.numberOfLines = 0;
    self.errorLabel.textAlignment = NSTextAlignmentCenter;
    self.errorLabel.hidden = YES;
    [self.cardView addSubview:self.errorLabel];
    [self.errorLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.offset(24);
        make.left.offset(20);
        make.right.offset(-20);
        make.bottom.offset(-24);
    }];
    
    // 确认租借按钮
    self.confirmBtn = [[QMUIButton alloc] init];
    [self.confirmBtn setTitle:Localized(@"scan_result_confirmRent") forState:UIControlStateNormal];
    [self.confirmBtn setTitleColor:UIColorWhite forState:UIControlStateNormal];
    self.confirmBtn.titleLabel.font = [UIFont fontB:17];
    self.confirmBtn.backgroundColor = UIColorMakeWithRGBA(255, 165, 0, 1); // 橙色
    self.confirmBtn.layer.cornerRadius = 8;
    self.confirmBtn.layer.masksToBounds = YES;
    [self.confirmBtn addTarget:self action:@selector(confirmRent) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.confirmBtn];
    [self.confirmBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(14);
        make.right.offset(-14);
        make.bottom.equalTo(self.view).offset(-(kSafeAreaBottomHeight + 12));
        make.height.mas_equalTo(48);
    }];
    
    // 再次扫码按钮（默认隐藏，设备不存在时显示）
    self.scanAgainBtn = [[QMUIButton alloc] init];
    [self.scanAgainBtn setTitle:Localized(@"scan_result_scanAgain") forState:UIControlStateNormal];
    [self.scanAgainBtn setTitleColor:UIColorWhite forState:UIControlStateNormal];
    self.scanAgainBtn.titleLabel.font = [UIFont fontB:17];
    self.scanAgainBtn.backgroundColor = UIColorMakeWithRGBA(255, 165, 0, 1); // 橙色
    self.scanAgainBtn.layer.cornerRadius = 8;
    self.scanAgainBtn.layer.masksToBounds = YES;
    [self.scanAgainBtn addTarget:self action:@selector(scanAgain) forControlEvents:UIControlEventTouchUpInside];
    self.scanAgainBtn.hidden = YES; // 默认隐藏
    [self.view addSubview:self.scanAgainBtn];
    [self.scanAgainBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(14);
        make.right.offset(-14);
        make.bottom.equalTo(self.view).offset(-(kSafeAreaBottomHeight + 12));
        make.height.mas_equalTo(48);
    }];
}

/// 创建适配接口选项
- (UIView *)createAdapterItem:(NSString *)title icon:(NSString *)iconName {
    UIView *itemView = [[UIView alloc] init];
    
    // 加载本地图标文件
    UIImageView *iconView = [[UIImageView alloc] init];
    UIImage *iconImage = nil;
    
    // 方式1: 直接使用图片名（如果图片已经添加到bundle中）
    iconImage = [UIImage imageNamed:iconName];
    
    // 方式2: 如果找不到，尝试从指定目录加载
    if (!iconImage) {
        NSString *imagePath = [[NSBundle mainBundle] pathForResource:iconName ofType:@"jpg" inDirectory:@"Class/Scan/Controller"];
        if (imagePath) {
            iconImage = [UIImage imageWithContentsOfFile:imagePath];
        }
    }
    
    // 方式3: 尝试从项目路径加载（开发环境）
    if (!iconImage) {
        NSString *projectPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:iconName];
        projectPath = [projectPath stringByAppendingPathExtension:@"jpg"];
        if ([[NSFileManager defaultManager] fileExistsAtPath:projectPath]) {
            iconImage = [UIImage imageWithContentsOfFile:projectPath];
        }
    }
    
    // 如果都找不到，使用占位图并打印日志
    if (!iconImage) {
        NSLog(@"⚠️ 找不到图标文件: %@.jpg，请确保图片已添加到Xcode项目中", iconName);
        iconImage = [UIImage imageNamed:@"home_help"];
    } else {
        NSLog(@"✅ 成功加载图标: %@.jpg", iconName);
    }
    
    iconView.image = iconImage;
    iconView.contentMode = UIViewContentModeScaleAspectFit;
    [itemView addSubview:iconView];
    [iconView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.offset(0);
        make.centerX.offset(0);
        make.width.height.mas_equalTo(32);
    }];
    
    // 标题
    QMUILabel *titleLabel = [[QMUILabel alloc] init];
    titleLabel.text = title;
    titleLabel.font = [UIFont fontM:14];
    titleLabel.textColor = UIColor.qd_titleTextColor;
    titleLabel.textAlignment = NSTextAlignmentCenter;
    [itemView addSubview:titleLabel];
    [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(iconView.mas_bottom).offset(4);
        make.left.right.offset(0);
        make.height.mas_equalTo(20);
    }];
    
    // 开关（写死为开启状态）
    UISwitch *switchView = [[UISwitch alloc] init];
    switchView.on = YES; // 写死为开启
    switchView.enabled = NO; // 禁用交互
    switchView.onTintColor = UIColorMakeWithRGBA(76, 175, 80, 1); // 绿色
    [itemView addSubview:switchView];
    [switchView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(titleLabel.mas_bottom).offset(4);
        make.centerX.offset(0);
    }];
    
    return itemView;
}


#pragma mark - Network Request
- (void)requestData {
    if (!self.deviceId || self.deviceId.length == 0) {
        [BRHud showAuto:Localized(@"scan_result_deviceIdEmpty") inView:self.view];
        return;
    }
    
    [BRHud showInView:self.view];
    
    NSString *urlStr = [BRAPI rentboxShowV2:self.deviceId];
    [[BRRequestManager shared] GET:urlStr params:nil succeed:^(NSDictionary * _Nonnull dataDict, NSInteger respCode) {
        [BRHud hiddenInView:self.view];
        
        // 检查数据是否在data字段中，如果没有则直接使用dataDict
        NSDictionary *data = dataDict[@"data"];
        if (!data || [data isKindOfClass:[NSNull class]]) {
            // 如果data字段不存在或为空，尝试直接使用dataDict（接口可能直接返回数据）
            if ([dataDict[@"mob"] isKindOfClass:[NSString class]] || 
                [dataDict[@"rentbox"] isKindOfClass:[NSDictionary class]] ||
                [dataDict[@"config"] isKindOfClass:[NSDictionary class]]) {
                // 如果dataDict包含接口字段，说明数据直接返回，没有嵌套在data中
                data = dataDict;
            } else {
                NSLog(@"⚠️ 接口返回数据格式错误，dataDict: %@", dataDict);
                // 设置错误码（非3840的其他错误）
                self.errorCode = -1;
                // 显示错误卡片
                [self showErrorCard:Localized(@"scan_result_scanFailed")];
                // 显示再次扫码按钮
                [self showScanAgainButton];
                return;
            }
        }
        
        NSLog(@"✅ 解析数据: %@", data);
        self.resultModel = [BRScanResultModel mj_objectWithKeyValues:data];
        
        // 检查设备是否存在（如果resultModel为空或关键字段为空，认为设备不存在）
        if (!self.resultModel || !self.resultModel.rentbox) {
            NSLog(@"⚠️ 设备不存在，resultModel: %@", self.resultModel);
            // 设置错误码（非3840的其他错误）
            self.errorCode = -1;
            // 显示错误卡片
            [self showErrorCard:Localized(@"scan_result_scanFailed")];
            // 显示再次扫码按钮
            [self showScanAgainButton];
            return;
        }
        
        // 设备存在，重置错误码
        self.errorCode = 0;
        // 显示确认租借按钮
        [self showConfirmButton];
        // 显示正常内容（隐藏错误信息）
        [self showNormalContent];
        [self updateUI];
        
    } failed:^(NSInteger code, NSString * _Nonnull errMsg) {
        [BRHud hiddenInView:self.view];
        NSLog(@"⚠️ 请求机柜详情失败: code=%ld, msg=%@", (long)code, errMsg);
        
        // 记录错误码
        self.errorCode = code;
        
        // 根据错误码显示不同的错误信息
        NSString *errorMessage = nil;
        if (code == 3840) {
            // 3840错误：当前有正在进行中的订单或未支付的订单
            errorMessage = Localized(@"scan_result_hasOrderError");
        } else {
            // 其他错误：扫码失败，请重试
            errorMessage = Localized(@"scan_result_scanFailed");
        }
        
        // 显示错误卡片
        [self showErrorCard:errorMessage];
        // 显示按钮（根据错误码显示不同的按钮）
        [self showScanAgainButton];
    }];
}

#pragma mark - Update UI
- (void)updateUI {
    if (!self.resultModel) {
        return;
    }
    
    // 更新顶部图片（优先使用本地图片，如果没有则使用ADList的第一张图片）
    UIImage *localImage = nil;
    // 方式1: 尝试直接使用图片名（如果图片在bundle中）
    localImage = [UIImage imageNamed:@"64217baca49f7eb9b7e7abc1f8c1dae6"];
    // 方式2: 如果方式1失败，尝试从文件系统加载
    if (!localImage) {
        NSString *imagePath = [[NSBundle mainBundle] pathForResource:@"64217baca49f7eb9b7e7abc1f8c1dae6" ofType:@"jpg"];
        if (imagePath) {
            localImage = [UIImage imageWithContentsOfFile:imagePath];
        }
    }
    // 方式3: 如果还是找不到，尝试从指定目录加载
    if (!localImage) {
        NSString *imagePath = [[NSBundle mainBundle] pathForResource:@"64217baca49f7eb9b7e7abc1f8c1dae6" ofType:@"jpg" inDirectory:@"Class/Scan/Controller"];
        if (imagePath) {
            localImage = [UIImage imageWithContentsOfFile:imagePath];
        }
    }
    
    if (localImage) {
        self.topImageView.image = localImage;
    } else if (self.resultModel.ADList.count > 0) {
        BRAdModel *adModel = self.resultModel.ADList[0];
        if (adModel.url1 && adModel.url1.length > 0) {
            [self.topImageView sd_setImageWithURL:[NSURL URLWithString:adModel.url1] placeholderImage:[UIImage imageNamed:@"home_help"]];
        }
    }
    
    // 更新计费规则
    if (self.resultModel.config) {
        self.billingRulesLabel.attributedText = [self formatBillingRules:self.resultModel.config];
    } else {
        // 如果没有配置，显示默认规则
        NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
        paragraphStyle.lineHeightMultiple = 1.6;
        UIFont *ruleFont = [UIFont fontM:12];
        UIColor *ruleColor = UIColorMakeWithRGBA(102, 102, 102, 1);
        NSDictionary *attributes = @{
            NSFontAttributeName: ruleFont,
            NSForegroundColorAttributeName: ruleColor,
            NSParagraphStyleAttributeName: paragraphStyle
        };
        NSString *defaultRules = [NSString stringWithFormat:@"%@\n%@\n%@\n%@", 
                                  [NSString stringWithFormat:Localized(@"scan_result_freeMinutes"), 5],
                                  [NSString stringWithFormat:Localized(@"scan_result_firstMinuteFee"), @"0"],
                                  [NSString stringWithFormat:Localized(@"scan_result_cycleFee"), @"1", 30],
                                  [NSString stringWithFormat:Localized(@"scan_result_dayFee"), @"30"]];
        self.billingRulesLabel.attributedText = [[NSAttributedString alloc] initWithString:defaultRules attributes:attributes];
    }
}

/// 格式化计费规则文本（参考前端代码格式）
- (NSAttributedString *)formatBillingRules:(BRRentConfigModel *)config {
    NSMutableAttributedString *rules = [[NSMutableAttributedString alloc] init];
    
    // 设置段落样式：行高1.6，字体12px，颜色#666
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    paragraphStyle.lineHeightMultiple = 1.6;
    UIFont *ruleFont = [UIFont fontM:12];
    UIColor *ruleColor = UIColorMakeWithRGBA(102, 102, 102, 1); // #666
    
    NSDictionary *attributes = @{
        NSFontAttributeName: ruleFont,
        NSForegroundColorAttributeName: ruleColor,
        NSParagraphStyleAttributeName: paragraphStyle
    };
    
    if (config) {
        // 免费分钟数
        NSInteger minuteFree = config.minuteFree > 0 ? (int)config.minuteFree : 5;
        NSString *freeMinutesText = [NSString stringWithFormat:Localized(@"scan_result_freeMinutes"), (int)minuteFree];
        [rules appendAttributedString:[[NSAttributedString alloc] initWithString:freeMinutesText attributes:attributes]];
        
        // 首分钟费用（直接使用接口返回的值，格式化）
        CGFloat firstMinuteFee = config.fistMinuteFee;
        NSString *firstMinuteText = [NSString stringWithFormat:Localized(@"scan_result_firstMinuteFee"), [BRTools br_formatVietnameseDong:firstMinuteFee]];
        [rules appendAttributedString:[[NSAttributedString alloc] initWithString:firstMinuteText attributes:attributes]];
        
        // 周期费用（直接使用接口返回的值，格式化）
        CGFloat cycleFee = config.cycleFee;
        NSInteger minuteCycle = config.minuteCycle > 0 ? (int)config.minuteCycle : 30;
        NSString *cycleFeeText = [NSString stringWithFormat:Localized(@"scan_result_cycleFee"), [BRTools br_formatVietnameseDong:cycleFee], (int)minuteCycle];
        [rules appendAttributedString:[[NSAttributedString alloc] initWithString:cycleFeeText attributes:attributes]];
        
        // 每日费用（直接使用接口返回的值，格式化）
        CGFloat dayFee = config.dayFee;
        NSString *dayFeeText = [NSString stringWithFormat:Localized(@"scan_result_dayFee"), [BRTools br_formatVietnameseDong:dayFee]];
        [rules appendAttributedString:[[NSAttributedString alloc] initWithString:dayFeeText attributes:attributes]];
        
        // 押金（直接使用接口返回的值，格式化）
        CGFloat securityFee = config.securityFee;
        NSString *securityFeeText = [NSString stringWithFormat:Localized(@"scan_result_securityFee"), [BRTools br_formatVietnameseDong:securityFee]];
        [rules appendAttributedString:[[NSAttributedString alloc] initWithString:securityFeeText attributes:attributes]];
        
        // 如果有首次免费，显示首次免费信息（这里暂时不显示，因为接口没有这个字段）
        // if (config.securityFree) {
        //     NSString *firstTimeFreeText = @"• 首次免费\n";
        //     [rules appendAttributedString:[[NSAttributedString alloc] initWithString:firstTimeFreeText attributes:attributes]];
        // }
    } else {
        // 默认计费规则（如果config为空）
        NSString *defaultRules = [NSString stringWithFormat:@"%@\n%@\n%@\n%@\n", 
                                  [NSString stringWithFormat:Localized(@"scan_result_freeMinutes"), 5],
                                  [NSString stringWithFormat:Localized(@"scan_result_firstMinuteFee"), @"0"],
                                  [NSString stringWithFormat:Localized(@"scan_result_cycleFee"), @"1", 30],
                                  [NSString stringWithFormat:Localized(@"scan_result_dayFee"), @"30"]];
        [rules appendAttributedString:[[NSAttributedString alloc] initWithString:defaultRules attributes:attributes]];
    }
    
    // 移除最后一个换行符
    if (rules.length > 0) {
        NSRange lastRange = NSMakeRange(rules.length - 1, 1);
        NSString *lastChar = [rules.string substringWithRange:lastRange];
        if ([lastChar isEqualToString:@"\n"]) {
            [rules deleteCharactersInRange:lastRange];
        }
    }
    
    return rules.length > 0 ? [rules copy] : [[NSAttributedString alloc] initWithString:Localized(@"scan_result_noBillingRules") attributes:attributes];
}


#pragma mark - Action
- (void)confirmRent {
    NSLog(@"📍 确认租借，deviceId: %@", self.deviceId);
    
    // 跳转到租借订单页面
    BRRentOrderViewController *rentOrderVC = [[BRRentOrderViewController alloc] init];
    rentOrderVC.deviceId = self.deviceId;
    rentOrderVC.powerBankType = 0; // 默认0，如果需要可以从接口获取
    // 押金金额将从接口获取，不需要在这里传递
    
    [self.navigationController pushViewController:rentOrderVC animated:YES];
}

/// 再次扫码或返回首页（根据错误码决定）
- (void)scanAgain {
    if (self.errorCode == 3840) {
        // 3840错误：跳转到首页
        NSLog(@"📍 错误码3840，跳转到首页");
        [self navigateToHome];
    } else {
        // 其他错误：返回上一页
        NSLog(@"📍 再次扫码，返回上一页");
        [self.navigationController popViewControllerAnimated:YES];
    }
}

/// 跳转到首页
- (void)navigateToHome {
    // 获取根视图控制器
    UIViewController *rootVC = [UIApplication sharedApplication].keyWindow.rootViewController;
    
    // 如果是导航控制器，pop到根视图
    if ([rootVC isKindOfClass:[UINavigationController class]]) {
        UINavigationController *nav = (UINavigationController *)rootVC;
        [nav popToRootViewControllerAnimated:YES];
    } else if ([rootVC isKindOfClass:[UITabBarController class]]) {
        // 如果是TabBar控制器，切换到首页tab
        UITabBarController *tabBarController = (UITabBarController *)rootVC;
        tabBarController.selectedIndex = 0;
        // 如果首页是导航控制器，pop到根视图
        if ([tabBarController.selectedViewController isKindOfClass:[UINavigationController class]]) {
            UINavigationController *nav = (UINavigationController *)tabBarController.selectedViewController;
            [nav popToRootViewControllerAnimated:YES];
        }
    } else {
        // 其他情况，尝试pop当前导航控制器的所有视图
        if (self.navigationController) {
            [self.navigationController popToRootViewControllerAnimated:YES];
        }
    }
}

/// 显示确认租借按钮，隐藏再次扫码按钮
- (void)showConfirmButton {
    self.confirmBtn.hidden = NO;
    self.scanAgainBtn.hidden = YES;
}

/// 显示再次扫码按钮或返回首页按钮，隐藏确认租借按钮
- (void)showScanAgainButton {
    self.confirmBtn.hidden = YES;
    self.scanAgainBtn.hidden = NO;
    
    // 根据错误码设置不同的按钮标题
    if (self.errorCode == 3840) {
        // 3840错误：显示"返回首页"
        [self.scanAgainBtn setTitle:Localized(@"scan_result_backToHome") forState:UIControlStateNormal];
    } else {
        // 其他错误：显示"再次扫码"
        [self.scanAgainBtn setTitle:Localized(@"scan_result_scanAgain") forState:UIControlStateNormal];
    }
}

/// 显示错误卡片（隐藏正常内容，显示错误信息）
- (void)showErrorCard:(NSString *)errorMessage {
    // 隐藏正常内容
    self.adapterTitleLabel.hidden = YES;
    self.adapterContainer.hidden = YES;
    self.billingTitleLabel.hidden = YES;
    self.billingRulesLabel.hidden = YES;
    
    // 显示错误信息
    self.errorLabel.text = errorMessage;
    self.errorLabel.hidden = NO;
}

/// 显示正常内容（隐藏错误信息，显示正常内容）
- (void)showNormalContent {
    // 显示正常内容
    self.adapterTitleLabel.hidden = NO;
    self.adapterContainer.hidden = NO;
    self.billingTitleLabel.hidden = NO;
    self.billingRulesLabel.hidden = NO;
    
    // 隐藏错误信息
    self.errorLabel.hidden = YES;
}

@end

